import { ref, onMounted, type Ref, onUnmounted } from 'vue'
import {
  cancelOrder,
  deleteOrder,
  follow,
  getPrescriptionPic
} from '@/api/consult'
import type { CodeType } from '@/types/user'
import { showToast, type FormInstance } from 'vant'
import { getMedicalOrderDetail } from '@/api/order'
import type { OrderDetail } from '@/types/order'
import type { ConsultOrderItem, Doctor, FollowType } from '@/types/consult'
import { showFailToast, showImagePreview, showSuccessToast } from 'vant'
import { OrderType } from '@/enums'
import { getCode } from '@/api/user'
//关注
export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  const followDoctor = async (item: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await follow({ type, id: item.id })
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    followDoctor
  }
}

// 查看处方
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return {
    showPrescription
  }
}

//取消订单
export const useCancelOrder = () => {
  // 取消订单按钮loading
  const loading = ref(false)
  // 取消按钮
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    cancelConsultOrder
  }
}

//删除订单
export const useDeleteOrder = (cb: () => void) => {
  // 删除订单按钮loading
  const deleteLoading = ref(false)
  // 删除订单
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    deleteLoading.value = true
    try {
      await deleteOrder(item.id)
      cb()
      showSuccessToast('删除成功')
    } catch (error) {
      showFailToast('删除失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return { deleteLoading, deleteConsultOrder }
}

export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  onMounted(async () => {
    const res = await getMedicalOrderDetail(id)
    order.value = res.data
  })
  return { order }
}

//发送验证码
export const useSendMobileCode = (mobile: string, type: CodeType = 'login') => {
  //倒计时定时器
  let timeId: number
  //表单实例
  const form = ref<FormInstance>()
  //时间倒计时
  let time = ref(0)
  //发送验证码
  const send = async () => {
    if (time.value > 0) return
    await form.value?.validate('mobile')
    await getCode(mobile, type) // 发送验证码
    showToast('发送成功')
    time.value = 60
    timeId = setInterval(() => {
      time.value--
      if (time.value <= 0) clearInterval(timeId)
    }, 1000)
  }

  return { form, time, send }
  onUnmounted(() => {
    clearInterval(timeId)
  })
}
